<template>
  <div class="excel-container">
    <upload-excel
      :before-upload="beforeUpload"
      :on-success="onSuccess"
    ></upload-excel>
  </div>
</template>

<script>
import UploadExcel from "@/components/UploadExcel";
import { batchEmployee } from "@/api/employee";
export default {
  name: "ImportExcel",
  components: {
    UploadExcel,
  },
  created() {
    const arr = [
      { 姓名: "zhangsan", 年龄: 18 },
      { 姓名: "lisi", 年龄: 19 },
    ];
    const relation = {
      姓名: "name",
      年龄: "age",
    };
    console.log(this.transData(arr, relation));
  },
  methods: {
    //文件上传之前，对文件做格式和大小的校验
    beforeUpload(file) {
      console.log("上传文件之前，对文件做格式和大小的验证", file);
      //文件格式和大小的校验
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (isLt1M) {
        //选择的文件小于 1M, return true，表示校验通过
        return true;
      }
      this.$message.warning("文件体积不能超过1M");
      //return true,表示校验不通过
      return false;
    },
    async onSuccess({ header, results }) {
      //header 表头数据
      //results 表体数据
      console.log("文件上传完成", header, results);
      //中英文对照关系
      const headerRelation = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        工号: "workNumber",
        聘用形式: "formOfEmployment",
        部门: "departmentName",
      };
      const data = this.transData(results, headerRelation);
      console.log(data)
      await batchEmployee(data);
      //提示用户
      this.$message.success("批量导入员工成功");
    },
    //数据转换工作
    transData(data,relation){
        //data:要转换的数据
        //relation：中英对照关系
        const arr = []
        data.forEach(item => {
            const obj = {}
            for(const key in item){
                //key:'姓名'
                //enkey:'name'
                const enkey = relation[key]
                //item['姓名']:'zhangsan'
                //obj['name'] = item['姓名']
                obj[enkey] = item[key]
            }
            arr.push(obj)
        })
        return arr
    }
  },
};
</script>

<style lang="scss" scoped>
.excel-container {
  padding: 50px;
}
</style>